<?php
require_once('include/check.php');
require_once("include/dict.php");
$dict = new DictionaryController($config);
$types = $dict->GetDictionary("support_type", false);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="http://api-maps.yandex.ru/2.0.30/?load=package.full,coordSystem.geo&lang=ru-RU"
        type="text/javascript"></script>
<script src="js/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="js/json.js" type='text/javascript'></script>
<script src="js/jquery-ui.min.js" type="text/javascript"></script>
<script src="js/util_script.js" type="text/javascript"></script>
<script src="js/jquery.editable.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="js/jquery.flot.js" type="text/javascript"></script>
<script src="js/jquery.flot.axislabels.js" type="text/javascript"></script>
<link href="css/styles.css" rel="stylesheet" type="text/css"/>
<link href="css/jquery-ui.css" rel="stylesheet" type="text/css"/>
<link href="css/jquery.dataTables.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript">
var user_token = '<?= $user_id ?>';
<?php if (isset($location)) : ?>
var default_location = <?= $location ?>;
var default_zoom = <?= $zoom ?>;
var default_layer = <?= $layer ?>;
<?php else: ?>
var default_location = [55.88, 36.87585];
var default_zoom = 12;
var default_layer = 1;
<?php endif; ?>

function setPointsDrag(enabled) {
    state = enabled ? "move" : null;
    map.geoObjects.each(function (obj) {
        if (obj.geometry.getType() == "Point") {
            if (enabled) {
                obj.events.add("dragstart", pointDragStart);
                obj.events.add("dragend", pointDragEnd);
                obj.options.set("draggable", true);
            } else {
                obj.events.remove("dragstart", pointDragStart);
                obj.events.remove("dragend", pointDragEnd);
                obj.options.set("draggable", false);
            }
        }
    });
}

function newCable() {
    var src = "cable_form.php";
    $('#cable iframe').css("display", "none");
    $('#cable iframe').attr("src", src);
    $('#cable iframe').load(function () {
        $('#cable iframe').css("display", "block");
    });
    $("#cable").dialog("open");
}

function toggleMoveButtons() {
    $("#saveNetwork").toggle();
    $("#editNetwork").toggle();
    $("#cancelEdit").toggle();
}

$(document).ready(function () {
    $("button").button().css("width", "180px");
    $("#addRoute").click(function () {
        cursor = map.cursors.push('crosshair');
        map.events.add('click', startPolylineDrawing);
        state = 'edit';
        $("#end-route").css("display", "block");
    });

    $(window).unload(rememberLocation);

    $("img.img-switch").click(function () {
        var t = $("#route_from").val();
        $("#route_from").val($("#route_to").val());
        $("#route_to").val(t);
    });

    $("#end-route").click(function () {
        if (state == 'edit')
            endDrawing();
        else if (state == 'add') {
            cursor.remove();
            $("#end-route").hide();
            map.events.remove('click', addPointArrayHandler);
            state = null;
        }
    });

    $("#addPoint").click(function () {
        $("#add_point_dialog").dialog("open");
    });



    $("#addPointOk").click(function () {
        cursor = map.cursors.push('crosshair');
        state = 'add';
        if ($("input[name=point_add_mode]:checked").val() == "single") {
            map.events.add('click', addPointHandler);
        } else {
            map.events.add('click', addPointArrayHandler);
            $("#end-route").show();
        }
        $("#add_point_dialog").dialog("close");
    });

    $("#editNetwork").click(function () {
        setPointsDrag(true);
        toggleMoveButtons();
    });

    $("input[name=point_add_mode]:radio").change(function () {
        if (this.value == 'single')
            $("#point_type").hide();
        else
            $("#point_type").show();
    });

    $("#saveNetwork").click(function () {
        toggleMoveButtons();
        setPointsDrag(false);
        updateNetwork();
    });

    $("#cancelEdit").click(function () {
        toggleMoveButtons();
        setPointsDrag(false);
        cancelNetwork();
    });

    $("#cancelAddPoint").click(function () {
        $("#add_point_dialog").dialog("close");
    });

    $("#cable").dialog({
        autoOpen: false,
        width: 820,
        height: 600,
        title: 'Информация о кабеле',
    });
    $("#route-details").dialog({
        autoOpen: false,
        width: 950,
        height:500,
        title: "Детали маршрута"
    });
    $("body").bind("cableSaved", cableSaved);

    $("#mapLayer").change(function () {
        refreshMap();
        bindSolver();
    });

    $("#point_container").dialog({
        autoOpen: false,
        width: 'auto',
        height: 'auto',
        title: 'Точка опоры',
    });
    $("#segment_container").dialog({
        autoOpen: false,
        width: 600,
        height: 350,
        title: 'Сегмент',
    });

    $("#connection_container").dialog({
        autoOpen: false,
        resizable: false,
        width: 'auto',
        height: 'auto',
        title: 'Схема соединения'
    });

    $("#add_point_dialog").dialog({
        autoOpen: false,
        width: 400,
        height: 180,
        title: 'Добавить опоры'
    });

    $("#solve").click(solveRoute);
    $("#clear-solve").click(clearRoute);
    $("#route_from, #route_to").change(highlightPoint);

    initRouteDialog();
    bindCables();
    $("body").bind("pointSaved", function () {
        refreshMap($("#point_container"));
    });
    $("body").bind("pointDeleted", function () {
        refreshMap($("#point_container"));
    });
    $("body").bind("segmentSaved", function () {
        refreshMap($("#segment_container"));
    });
    $("body").bind("segmentDeleted", function () {
        refreshMap($("#segment_container"));
    });
    $("body").bind("openPoint", function (e) {
        openPointDialog(e.id);
    });
    $("body").bind("connection", function (e) {
        openConnection(e.id, e.cid ? e.cid : null, e.create ? true : false, e.canSaveConnection ? true : false);
    });

    $("body").bind("connectionSaved", function (e) {
        if (e.close)
            $("#connection_container").dialog("close");
        $('#point_container iframe').attr('src', function (i, val) {
            return val;
        });
    });
    $("body").bind("connectPointRemoved", function (e) {
        $("#connection_container").dialog("close");
        $('#point_container iframe').attr('src', function (i, val) {
            return val;
        });
    });
    ymaps.ready(initMap);
});

function cableSaved() {
    $("#cable").dialog("close");
    alert("Кабель сохранен");
    bindCables();
}

function bindCables() {
    $.ajax({
        method: "POST",
        url: "include/cable_controller.php",
        data: {
            op: "list"
        }
    }).done(function (response) {
        $cables = JSON.parse(response);
        $("#route-cable").html("");
        $.each($cables, function (id, title) {
            $("#route-cable").append($('<option></option>').val(id).html(title));
        });
    });
}

</script>
</head>
<body>
<table width="100%">
    <tr>
        <td valign="top" width="20%"><?php
            include("include/menu.php")
            ?></td>
        <td width="60%" align="center">
            <div class="main">
                <b>Слой:&nbsp;</b>
                <select id='mapLayer'>
                    <option value='1'>Факт</option>
                    <option value='2'>План</option>
                    <option value='3'>Все</option>
                </select>

                <div id="mapContainer" style="position:relative">
                    <div id="map" style="width: 800px; height: 600px"></div>
                    <br/>
                    <table width="100%">
                        <tr>
                            <td align='center' width="25%">
                                <button id="addRoute">
                                    Добавить маршрут
                                </button>
                            </td>
                            <td align="center" width="25%" align="center">
                                <button id="addPoint">
                                    Добавить точку опоры
                                </button>
                            </td>
                            <td width="25%" align="center">
                                <button id="editNetwork">
                                    Редактировать схему
                                </button>
                                <button id="saveNetwork" style="display: none">
                                    Сохранить изменения
                                </button>
                            </td>
                            <td align="center" width="25%">
                                <button id="cancelEdit" style="display: none">
                                    Отмена
                                </button>
                                <button id="end-route" style="display:none">
                                    Закончить построение
                                </button>
                            </td>
                        </tr>
                    </table>
                </div>
                <div id="route-edit-form">
                    <input type="hidden" id="route-id"/>
                    <b>Общая длина:</b>&nbsp;<span id="route-length"></span>
                    <br/>
                    <br/>
                    <b>Точек опоры:</b>&nbsp;<span id="route-points"></span>
                    <br/>
                    <br/>
                    <b>Используемый кабель:</b>&nbsp; <select id="route-cable"></select>
                    &nbsp;<a href="javascript:void(0)" onclick="newCable();">Новый кабель</a>
                    <br/>
                </div>
            </div>
        </td>
        <td width="20%" valign="top">
            <div class="solver" id="solver-block">
                <b>Расчет маршрута</b><br/><br/>
                <table>
                    <tr>
                        <td>От:</td>
                        <td><select id="route_from"></select></td>
                        <td rowspan="2" valign="middle">
                            <img src="images/switch.png" class="img-switch">
                        </td>
                    </tr>
                    <tr>
                        <td>До:</td>
                        <td><select id="route_to"></select></td>
                    </tr>
                </table>

                <button id="solve">Расcчитать</button>
                <br/>
                <button id="clear-solve">Очистить</button>
                <div id="route-info" style="display: none">
                 </div>
                <div id="route-details">
                    <div class="route-path">

                    </div>
                    <div class="route-plot">

                    </div>
                </div>
            </div>
        </td>
    </tr>
</table>
<div id="add_point_dialog">
    Добавить опоры:<br/>
    <input type='radio' name='point_add_mode' value='single' checked='checked'>Одну</input><br/>
    <input type='radio' name='point_add_mode' value='multi'>Много</input><br/>

    <div id="point_type" class='hidden'>Тип:
        <select id='point_type_select'>
            <?php
            foreach ($types as $key => $value)
                echo "<option value='$key'>$value</option>";
            ?>
        </select>
        <br/>
    </div>
    <button id='addPointOk'>ОК</button>
    <button id='cancelAddPoint' style='float:right'>Отмена</button>
</div>
<div id="point_container">
    <iframe src="" frameborder="no" width="570" height="500"></iframe>
</div>
<div id="cable" style="width:100%; height:100%; display:none">
    <iframe src="" frameborder="no" scrolling="no" width="800" height="500"></iframe>
</div>
<div id="segment_container">
    <iframe src="" frameborder="no" scrolling="no" width="570" height="300"></iframe>
</div>
<div id="connection_container">
    <!--<iframe id="frmConnectionContainer" src="" frameborder="no" scrolling="no" onload="ResizeIframe('frmConnectionContainer')"></iframe>-->
</div>
</body>
</html>